//package com.plian.system.service.fr.cluemanagement.impl;
//
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.plian.Tools.*;
//import com.plian.Tools.pagedata.PageData;
//import com.plian.system.constant.sys.FormStatusConstant;
//import com.plian.system.constant.sys.FormTypeConstant;
//import com.plian.system.dao.sys.orgzation.OrgzationDao;
//import com.plian.system.dao.sys.user.UserDao;
//import com.plian.system.entity.fr.cluemanagement.*;
//import com.plian.system.entity.sys.Message;
//import com.plian.system.mapper.fr.cluemanagement.*;
//import com.plian.system.mybatis.base.BaseFlowService;
//import com.plian.system.mybatis.base.BaseServiceImpl;
//import com.plian.system.mybatis.support.Condition;
//import com.plian.system.properties.GzwProperties;
//import com.plian.system.service.fr.cluemanagement.*;
//import com.plian.system.service.sys.code.IFormCodeService;
//import com.plian.system.service.sys.file.FileService;
//import com.plian.system.service.sys.message.IMessageService;
//import com.plian.system.service.wf.FormWorkflowService;
//import com.plian.system.vo.fr.cluemanagement.*;
//import com.plian.system.vo.sys.UserInfoVO;
//import com.plian.system.wrapper.fr.cluemanagement.*;
//import lombok.AllArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang.exception.ExceptionUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import javax.annotation.Resource;
//import java.util.*;
//
//import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;
//
//
//@Service
//@Slf4j
//@AllArgsConstructor
//public class ClueManagementServiceImpl extends BaseServiceImpl<ClueManagementMapper, ClueManagement> implements IClueManagementService, BaseFlowService {
//
//
//    private final IClueCollectService clueCollectService;
//    private final IClueVerificationOpinionService clueVerificationOpinionService;
//    private final IClueCompanyReviewService clueCompanyReviewService;
//    private final ICluePreProcessOpinionService cluePreProcessOpinionService;
//    private final IClueProcessResultService clueProcessResultService;
//    private final ClueManagementWrapper managementWrapper;
//    private final ClueCollectWrapper clueCollectWrapper;
//    private final ClueCollectMapper clueCollectMapper;
//    private final ClueVerificationOpinionMapper clueVerificationOpinionMapper;
//    private final ClueVerificationOpinionWrapper clueVerificationOpinionWrapper;
//    private final CluePreProcessOpinionMapper cluePreProcessOpinionMapper;
//
//    private final CluePreProcessOpinionSubMapper cluePreProcessOpinionSubMapper;
//    private final CluePreProcessOpinionWrapper cluePreProcessOpinionWrapper;
//    private final ClueCompanyReviewMapper clueCompanyReviewMapper;
//    private final ClueCompanyReviewWrapper clueCompanyReviewWrapper;
//    private final ClueProcessResultMapper clueProcessResultMapper;
//    private final ClueProcessResultWrapper clueProcessResultWrapper;
//
//    private final ICluePreProcessOpinionSubService cluePreProcessOpinionSubService;
//
//    private final CluePreProcessOpinionSubWrapper cluePreProcessOpinionSubWrapper;
//    private FormWorkflowService formWorkflowService;
//    private IFormCodeService formCodeService;
//    private FileService fileService;
//
//    @Resource
//    private GzwProperties gzwProperties;
//    @Autowired
//    private UserDao userDao;
//    @Autowired
//    private OrgzationDao orgzationDao;
//    @Resource
//    private IMessageService messageService;
//
//
//    @Transactional(rollbackFor = Throwable.class)
//    @Override
//    public boolean submit(ClueManagementVO clueManagementVO) {
//        try {
//            ClueManagement clueManagement = managementWrapper.voToEntity(clueManagementVO);
//            if (!Optional.ofNullable(clueManagement.getId()).isPresent()) {
//                clueManagement.setCode(formCodeService.getCode(FormTypeConstant.CLUE_COMPANY_PURSUE_DUTY));
//                clueManagement.setFormType(String.valueOf(FormTypeConstant.CLUE_COMPANY_PURSUE_DUTY));
//            }
//            //保存主表
//            super.saveOrUpdate(clueManagement);
//            /**
//             * 线索收集
//             */
//            ClueCollect clueCollect = clueCollectWrapper.voToEntity(clueManagementVO.getClueCollectVOS());
//            clueCollectService.submit(clueCollect, clueManagement);
//            /**
//             * 核查意见
//             */
//            ClueVerificationOpinion clueVerificationOpinion = clueVerificationOpinionWrapper.voToEntity(clueManagementVO.getClueVerificationOpinionVOS());
//            clueVerificationOpinionService.submit(clueVerificationOpinion, clueManagement);
//            if (StringUtil.isNotBlank(clueVerificationOpinion.getVerificationOpinion())) {
//                //发送消息
//                PageData pageData = new PageData();
//                pageData.put("id", clueManagement.getId());
//                pageData.put("formType", clueManagement.getFormType());
//                sendMessage(pageData);
//            }
//
//
//            /**
//             * 企业复核
//             */
//            ClueCompanyReview clueCompanyReview = clueCompanyReviewWrapper.voToEntity(clueManagementVO.getClueCompanyReviewVOS());
//            clueCompanyReviewService.submit(clueCompanyReview, clueManagement);
//            /**
//             * 预处理意见
//             */
//            CluePreProcessOpinion cluePreProcessOpinion = cluePreProcessOpinionWrapper.voToEntity(clueManagementVO.getCluePreProcessOpinionVOS());
//            cluePreProcessOpinionService.submit(cluePreProcessOpinion, clueManagement);
//            //预处理意见子表
//            List<CluePreProcessOpinionSub> cluePreProcessOpinionSubs = cluePreProcessOpinionSubWrapper.voToEntity(clueManagementVO.getCluePreProcessOpinionVOS().getCluePreProcessOpinionSubVOS());
//            if (CollectionUtil.isNotEmpty(cluePreProcessOpinionSubs)) {
//                cluePreProcessOpinionSubs.forEach(item -> {
//                    item.setClueManagementId(String.valueOf(clueManagement.getId()));
//                    item.setCluePreProcessOpinionId(String.valueOf(cluePreProcessOpinion.getId()));
//                });
//                cluePreProcessOpinionSubService.saveList(cluePreProcessOpinionSubs);
//            }
//            /**
//             * 处理结果
//             */
//            ClueProcessResult clueProcessResult = clueProcessResultWrapper.voToEntity(clueManagementVO.getClueProcessResultVOS());
//            clueProcessResultService.submit(clueProcessResult, clueManagement);
//            return true;
//        } catch (Exception e) {
//            log.error("error:保存或修改失败：{}", e);
//            throw new RuntimeException("保存修改失败");
//        }
//    }
//
//    /**
//     * 填写核查意见完成发送消息
//     *
//     * @param currData
//     */
//    public void sendMessage(PageData currData) {
//        List<Message> messages = new ArrayList<>();
//        //当前登陆用户（集团）
//        String orgId = TokenUtil.getTokenOrgId();
//        String userId = TokenUtil.getTokenUserId();
//        try {
//            PageData findbyid = userDao.findbyid(userId);
//            String userName = findbyid.getString("name");
//            //当前登录用户企业信息
//            PageData currOrgInfo = orgzationDao.findbyid(orgId);
//            String isunit = currOrgInfo.getString("isunit");
//            String orgName = currOrgInfo.getString("orgName");
//            if ("1".equals(isunit)) {
//                //下发国资委用户
//                PageData params = new PageData();
//                params.put("orgId", gzwProperties.getId());
//                params.put("funName", "核查意见");
//                List<UserInfoVO> userByGroup = userDao.findUserByConfigFunAndOrgId(params);
//                if (CollectionUtil.isNotEmpty(userByGroup)) {
//                    for (UserInfoVO userInfoVO : userByGroup) {
//                        //year（no） orgID 和name，
//                        Message message = Message.builder().formId(currData.getString("id")).orgName(orgName)
//                                .orgId(orgId).formType(currData.getString("formType")).formTypeName("企业责任追究").messageTime(DateUtil.now())
//                                .createUser(userInfoVO.getUserId()).message("已完成企业责任追究核查意见填报！").sendUser(userId).sendUserName(userName).isIgnore(0).build();
//
//                        messages.add(message);
//                    }
//                }
//            }
//
//            messageService.saveBatch(messages);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * 处理详情时的状态
//     *
//     * @param clueManagementVO
//     * @return
//     */
//    private ClueManagementVO getDetailNextCluStatus(ClueManagementVO clueManagementVO) {
//        List<ClueManagementVO> entityToVOS = new LinkedList<>();
//        entityToVOS.add(clueManagementVO);
//        List<ClueManagementVO> clueManagementVOS = transList(entityToVOS);
//        return clueManagementVOS.get(0);
//    }
//
//    @Override
//    public ClueManagementVO detail(ClueManagement clueManagement) {
//
//        ClueManagementVO managementVO = managementWrapper.entityToVO(getOne(Condition.getQueryWrapper(clueManagement)));
//        if (managementVO == null) {
//            return null;
//        }
//        ClueManagementVO clueManagementVO = getDetailNextCluStatus(managementVO);
//        Long clueManagementId = clueManagement.getId();
//        //线索收集
//        ClueCollect clueCollect = clueCollectMapper.selectOne(new LambdaQueryWrapper<ClueCollect>()
//                .eq(ClueCollect::getClueManagementId, clueManagementId));
//        ClueCollectVO clueCollectVO = new ClueCollectVO();
//        if (clueCollect != null) {
//            clueCollectVO = clueCollectWrapper.entityToVO(clueCollect);
//        }
//        clueManagementVO.setClueCollectVOS(clueCollectVO);
//
//        //核查意见
//        ClueVerificationOpinion clueVerificationOpinion = clueVerificationOpinionMapper.selectOne(new LambdaQueryWrapper<ClueVerificationOpinion>()
//                .eq(ClueVerificationOpinion::getClueManagementId, clueManagementId));
//        ClueVerificationOpinionVO clueVerificationOpinionVO = new ClueVerificationOpinionVO();
//        if (clueVerificationOpinion != null) {
//            clueVerificationOpinionVO = clueVerificationOpinionWrapper.entityToVO(clueVerificationOpinion);
//        }
//        clueManagementVO.setClueVerificationOpinionVOS(clueVerificationOpinionVO);
//
//        //预处理
//        CluePreProcessOpinion cluePreProcessOpinion = cluePreProcessOpinionMapper.selectOne(new LambdaQueryWrapper<CluePreProcessOpinion>()
//                .eq(CluePreProcessOpinion::getClueManagementId, clueManagementId));
//        CluePreProcessOpinionVO cluePreProcessOpinionVO = new CluePreProcessOpinionVO();
//        List<CluePreProcessOpinionSubVO> cluePreProcessOpinionSubVOS = new ArrayList<>();
//
//        if (cluePreProcessOpinion != null) {
//            cluePreProcessOpinionVO = cluePreProcessOpinionWrapper.entityToVO(cluePreProcessOpinion);
//            List<CluePreProcessOpinionSub> cluePreProcessOpinionSubs = cluePreProcessOpinionSubMapper.selectList(new LambdaQueryWrapper<CluePreProcessOpinionSub>()
//                    .eq(CluePreProcessOpinionSub::getCluePreProcessOpinionId, cluePreProcessOpinionVO.getId()));
//            if (CollectionUtil.isNotEmpty(cluePreProcessOpinionSubs)) {
//                cluePreProcessOpinionSubVOS = cluePreProcessOpinionSubWrapper.entityToVO(cluePreProcessOpinionSubs);
//            }
//        }
//        clueManagementVO.setCluePreProcessOpinionVOS(cluePreProcessOpinionVO);
//        cluePreProcessOpinionVO.setCluePreProcessOpinionSubVOS(cluePreProcessOpinionSubVOS);
//
//
//        //企业复核
//        ClueCompanyReview clueCompanyReview = clueCompanyReviewMapper.selectOne(new LambdaQueryWrapper<ClueCompanyReview>()
//                .eq(ClueCompanyReview::getClueManagementId, clueManagementId));
//        ClueCompanyReviewVO clueCompanyReviewVO = new ClueCompanyReviewVO();
//        if (clueCompanyReview != null) {
//            clueCompanyReviewVO = clueCompanyReviewWrapper.entityToVO(clueCompanyReview);
//        }
//        clueManagementVO.setClueCompanyReviewVOS(clueCompanyReviewVO);
//
//        //处理结果
//        ClueProcessResult clueProcessResult = clueProcessResultMapper.selectOne(new LambdaQueryWrapper<ClueProcessResult>()
//                .eq(ClueProcessResult::getClueManagementId, clueManagementId));
//        ClueProcessResultVO clueProcessResultVO = new ClueProcessResultVO();
//        if (clueProcessResult != null) {
//            clueProcessResultVO = clueProcessResultWrapper.entityToVO(clueProcessResult);
//        }
//        clueManagementVO.setClueProcessResultVOS(clueProcessResultVO);
//        return clueManagementVO;
//    }
//
//
//    @Override
//    public List<ClueManagementVO> transList(List<ClueManagementVO> entityToVOS) {
//        entityToVOS.forEach(item -> {
//            switch (item.getClueStatus()) {
//                case "158001":
//                    item.setNextClueStatus("158002");
//                    item.setNextClueStatusName("核查情况");
//                    break;
//                case "158002":
//                    item.setNextClueStatus("158003");
//                    item.setNextClueStatusName("企业复核");
//                    break;
//                case "158003":
//                    item.setNextClueStatus("158004");
//                    item.setNextClueStatusName("预处理");
//                    break;
//                case "158004":
//                    item.setNextClueStatus("158005");
//                    item.setNextClueStatusName("结果处理");
//                    break;
//                default:
//                    break;
//            }
//        });
//        return entityToVOS;
//    }
//
//    @Override
//    public boolean deleteLogic(List<Long> ids) {
//        for (Long id : ids) {
//            ClueManagement cluManagement = getById(id);
//            if (cluManagement == null) {
//                return false;
//            } else if (cluManagement.getStatus() != null &&
//                    (cluManagement.getStatus() != FormStatusConstant.STASH && cluManagement.getStatus() != FormStatusConstant.UNREVIEWED)) {
//                return false;
//            }
//            formWorkflowService.deleteProcessInstance(String.valueOf(id));
//        }
//        boolean result = super.deleteLogic(ids);
//        return result;
//    }
//
//    /**
//     * 审核完 生成处理结果
//     *
//     * @return
//     * @param:
//     * @date: 2023/4/7 4:14 PM
//     * @author: jatpeo
//     */
//    private void createProcessResult(String id) {
//        //查询预处理
//        CluePreProcessOpinion cluePreProcessOpinion = cluePreProcessOpinionMapper.selectOne(new LambdaQueryWrapper<CluePreProcessOpinion>().eq(CluePreProcessOpinion::getClueManagementId, id));
//        //预处理子表
//        List<CluePreProcessOpinionSub> cluePreProcessOpinionSubs = cluePreProcessOpinionSubMapper.selectList(new LambdaQueryWrapper<CluePreProcessOpinionSub>()
//                .eq(CluePreProcessOpinionSub::getClueManagementId, id));
//
//        if (Optional.ofNullable(cluePreProcessOpinion).isPresent()) {
//            ClueProcessResult clueProcessResult = clueProcessResultService.getOne(new LambdaQueryWrapper<ClueProcessResult>()
//                    .eq(ClueProcessResult::getClueManagementId, id));
//            if (Optional.ofNullable(clueProcessResult).isPresent()) {
//                clueProcessResult.setClueManagementId(id);
//                clueProcessResult.setDutyLeaderUsers(cluePreProcessOpinion.getDutyLeaderUsers());
//                clueProcessResult.setDutyLeaderProcessOpinion(cluePreProcessOpinion.getDutyLeaderProcessOpinion());
//                clueProcessResult.setDamageRecoveredAmount(cluePreProcessOpinion.getDamageRecoveredAmount());
//                if (CollectionUtil.isNotEmpty(cluePreProcessOpinionSubs)) {
//                    CluePreProcessOpinionSub cluePreProcessOpinionSub = cluePreProcessOpinionSubs.get(0);
//                    clueProcessResult.setDutyUsers(cluePreProcessOpinionSub.getDutyUsers());
//                    clueProcessResult.setDutyProcessOpinion(cluePreProcessOpinionSub.getDutyProcessOpinion());
//                }
//                clueProcessResultService.saveOrUpdate(clueProcessResult);
//            }
//        }
//
//    }
//
//    @Override
//    public HashMap<String, Object> commit(String id) {
//        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);
//        //将需要提交的流程变量返回，用于工作流侧
//        return new HashMap<String, Object>();
//    }
//
//    @Override
//    public Boolean finish(String id) {
//        //处理最后的结果
//        createProcessResult(id);
//        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
//    }
//
//    @Override
//    public Boolean reject(String id, int formState, String comment) {
//        //将状态进行还原为已预处理
//        try {
//            ClueManagement clueManagement = getById(id);
//            clueManagement.setStatus(formState);
//            clueManagement.setClueStatus("158004");
//            updateById(clueManagement);
//            return true;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//            return false;
//        }
//    }
//
//    @Override
//    public List<PageData> findByIds(List<String> formIds) {
//        List<ClueManagement> clueManagementList = list(new LambdaQueryWrapper<ClueManagement>()
//                .in(ClueManagement::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA))));
//        List<ClueManagementVO> clueManagementVOS = managementWrapper.entityToVO(clueManagementList);
//        List<PageData> pageDataList = new ArrayList<>();
//        try {
//            if (CollectionUtil.isNotEmpty(clueManagementVOS)) {
//                for (ClueManagementVO vo : clueManagementVOS) {
//                    PageData pd = new PageData();
//                    pd.put("id", vo.getId());
//                    pd.put("UNITNAME", vo.getUnitName());
//                    pd.put("APPLICANTNAME", vo.getCreateUser());
//                    pd.put("applicantId", vo.getCreateUser());
//                    pd.put("applyOrganizationId", vo.getUnitId());
//                    pd.put("formType", FormTypeConstant.CLUE_COMPANY_PURSUE_DUTY);
//                    pd.put("orgName", vo.getUnitName());
//                    pageDataList.add(pd);
//                }
//            }
//            return pageDataList;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//        }
//        return pageDataList;
//    }
//
//    @Override
//    public List<Integer> getFormType() {
//        return Arrays.asList(FormTypeConstant.CLUE_COMPANY_PURSUE_DUTY);
//    }
//
//    @Override
//    public void goBackToStash(String formId) {
//        handleStatus(Long.valueOf(formId), UNREVIEWED);
//    }
//
//    /**
//     * 统一处理状态机事件方法
//     *
//     * @param id           主键
//     * @param updateStatus 更新状态
//     * @return boolean
//     */
//    private Boolean handleStatus(Long id, int updateStatus) {
//        try {
//            ClueManagement clueManagement = getById(id);
//            if (updateStatus == FormStatusConstant.FINISH) {
//                clueManagement.setApprovedUser(TokenUtil.getTokenUserId());
//                Date now = DateUtil.now();
//                clueManagement.setApprovedTime(now);
//            }
//            clueManagement.setStatus(updateStatus);
//            updateById(clueManagement);
//            return true;
//        } catch (Exception e) {
//            log.error(ExceptionUtils.getFullStackTrace(e));
//            return false;
//        }
//    }
//}
